package com.googlecode.yoohoo.xep.register.protocol;

import java.util.List;

import com.googlecode.yoohoo.xep.data.protocol.Data;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.Attribute;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.IXmppParser;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.IXmppParserFactory;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.ProtocolKey;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.XmppParserAdapter;
import com.googlecode.yoohoo.xmppcore.protocol.stanza.error.BadRequest;
import com.googlecode.yoohoo.xmppcore.utils.ErrorUtils;

public class RegisterParserFactory implements IXmppParserFactory<Register> {

	@Override
	public IXmppParser<Register> createParser() {
		return new RegisterParser();
	}

	@Override
	public ProtocolKey getProtocolKey() {
		return Register.PROTOCOL_KEY;
	}
	
	private class RegisterParser extends XmppParserAdapter<Register> {
		private static final String PATH_QUERY = "query";
		private Register register;
		
		@Override
		public void processAttributes(String path, List<Attribute> attributes) {
			if (PATH_QUERY.equals(path)) {
				if (attributes.size() != 0) {
					throw ErrorUtils.createProtocolException("Attributes aren't allowed in 'query' element.",
							new BadRequest());
				}
				
				register = new Register();
			} else {
				throw ErrorUtils.createProtocolException(String.format("Invalid parsing path '%s'.",
						path), new BadRequest());
			}
		}

		@Override
		public Register getObject() {
			return register;
		}
	
		@Override
		public void processEmbeddedObject(ProtocolKey pk, Object object) {
			register.setData((Data)object);
		}
	}

}
